/*
 * @Author: wangxiaojie
 * @LastEditors: wangxiaojie
 */

// 数组处理
const oldArrayPrototype = Array.prototype
const proto = Object.create(oldArrayPrototype)

const arrList = ['push', 'pop', 'unshift', 'shift', 'sort', 'splice', 'reverse']

arrList.map(method => {
  proto[method] = function(...args) {
    console.log('修改数组', ...args)
    oldArrayPrototype[method].call(this, ...args)
  }
})


function reactive (data) {
  if (Array.isArray(data)) {
    data.__proto__ = proto
    return data
  }
  if (typeof data !== 'object' || data === '') {
    return data
  }

  Object.keys(data).map(key => {
    let val = data[key]
    // 递归调用
    reactive(val)
    Object.defineProperty(data, key, {
      enumerable: false, // 是否可枚举
      configurable: false, // 当且仅当该属性的 configurable 键值为 true 时，该属性的描述符才能够被改变，同时该属性也能从对应的对象上被删除。
      get: () => {
        return val
      },
      set: (newVal) => {
        if(newVal !== val) {
          console.log(`${key}: ${newVal}`)
          val = newVal
          reactive(newVal)
        }
      }
    })
  })
  return data
}

module.exports = {
  reactive
}

